#! usr/bin/python

from PyQt4 import QtGui,  QtCore
from PyQt4.QtCore import Qt
from matplotlib.widgets import Cursor
import numpy as np
import canvas_toolbar
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from core import clustering as clust
#matplotlib.rcParams['font.size'] = 9
import sys

from pylab import *

class canvasUi (QtGui.QWidget):
	
	__slots__ =('X', 'Y', 'fill_X', 'fill_Y', 'legends', 'flags')
	
	def __init__(self,X, Y, fill_X= None, fill_Y=None, legends =None, flags = "chrom", parent =None):
		
		"""
		Constructor with:
		X: absciss Data
		Y: ordonnee data
		fill: start point and end point for filling
		flags: chrom, spectr, or corr produce different kind of plot
		"""
		QtGui.QWidget.__init__(self, parent)		
		self.X=X
		self.Y=Y
		self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

		self.fill_X = fill_X
		self.fill_Y= fill_Y
		self.legends =legends
		self.flags =flags
		
		self.max = max(self.Y)
		
		self.makeGui()
		self.connect()
		
	def get_max_index(self):
		
		"""
		find index of max data for plotting rt on the plot
		"""
		
		max =0.; index =0
		for i, val in enumerate(self.Y[0]):
			if val > max:
				index=i
				max= val
		"""
		diff_y_value = (max *10)/100.
		diff_x_value = (self.X[0][index]*10)/100.
		points=[]
		for val1, val2 in zip(self.X[0], self.Y[0]):
			if (val2 > max-diff_y_value and val2 < max+diff_y_value) and (val1 <self.X[0][index]-diff_x_value or val1 >self.X[0][index]+diff_x_value ):
				points.append((val1, val2))
		return points
		"""
		return index
		
	def makeGui (self):
		
		"""
		produces the gui
		called in the constructor
		"""
		
		layout=QtGui.QVBoxLayout()
		self.fig=Figure(figsize=(5, 4), dpi=76, facecolor='w')
		#*******
		
		if self.flags == "chrom" or self.flags =="peak" :#
			sub = self.fig.add_subplot(111,axisbg='w',xlabel="Retention Time",ylabel="intensity")
		elif self.flags =="spectr":
			sub=self.fig.add_subplot(111,axisbg='w',xlabel="m/z",ylabel="intensity")
		elif self.flags =="corr":
			sub = self.fig.add_subplot(111,  axisbg ='w',  xlabel ="x",  ylabel ="y")
			
		sub.grid(True)
		plots =[]
		#rect = DraggableRectangle(sub)
		for i, val in enumerate(self.X):
			for j, val2 in enumerate(self.Y):
				if i==j:
					if self.flags =="chrom" or self.flags =="peak":#
						plots.append(sub.plot(val, val2,'-'))#plots.append
						#points = self.get_max_index()
						#for p in points:
						index =self.get_max_index()
						sub.annotate(str(self.X[0][index]), xy= (self.X[0][index],self.Y[0][index]),  xycoords='data')
						if self.fill_X and self.fill_Y:
							sub.fill_between(np.array(self.fill_X), np.array(self.fill_Y), facecolor ='red', alpha = 0.5)
	
					elif self.flags =="spectr":
						sub.bar(val,val2, width =0.1)
					
				if self.flags == "corr":
					if len(val) > len(val2):
						clust.value_elimination(val, val2)
					elif len(val) < (len(val2)):
						clust.value_elimination(val2,val)
					"""
					minus, maxus = min(val), max(val)
					mean1,mean2 =sum(val)/len(val), sum(val2)/len(val2)
					cova =0
					for i in xrange (len(val)):
						cova+= (val[i] -mean1)*(val2[i]-mean2)
					a =cova/len(val)
					b= mean2 -a*mean1
					x=[]; y=[]
					for i in xrange (int(minus),int(maxus)):
						x.append(i)
						y.append(a*i+b)
					sub.plot(x,y)
					"""
					sub.xcorr(val,val2, usevlines=True, maxlags=7, normed=True, lw=2)
						
		if self.flags == "chrom":				
			sub.legend(tuple(plots), self.legends, loc = 1)
						
		can=FigureCanvas(self.fig)
		#self.cursor =Cursor(sub, useblit=True, color='blue', linewidth=1 )
		can.setParent(self)
		self.mpl_toolbar = canvas_toolbar.modified_toolbar(can,self)
		layout.addWidget(can)
		layout.addWidget(self.mpl_toolbar)
		self.setLayout(layout)
	
	
	def connect (self):
		
		"""
		connection event matplotlib event
		"""
		
		self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)
		self.fig.canvas.mpl_connect('pick_event', self.on_pick)
	
	def on_motion(self, event):
		
		"""
		event mouse motion
		tooltip created
		"""
		'on motion we will move the rect if the mouse is over us'

		if event.xdata and self.mpl_toolbar._active != 'ZOOM' and self.mpl_toolbar._active != 'PAN':
			QtGui.QToolTip.showText(QtGui.QCursor.pos(), "x:"+str(event.xdata)+", y:"+str(event.ydata))#
			self.fig.canvas.draw()
	
	def on_pick(self, event):
		
		"""
		pick event
		click on the plot -> data dock_widget
		"""
		pass


if __name__== "__main__":
	app = QtGui.QApplication(sys.argv)
	x= [1,4,10,3,5]; y=[4,3,9,2,3]
	can = canvasUi(x, y)
	can.show()
	app.exec_()
 
